package com.example.scaffolding.util

import android.content.Context
import android.util.Log
import okhttp3.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

object HttpDownloader {
    private const val TAG = "HttpDownloader"

    fun download(context: Context, url: String, listener: EventListener<String>) {
        val file =
            File(context.filesDir.toString() + File.separator + System.currentTimeMillis())
        val client = OkHttpClient()
        val request: Request = Request.Builder().url(url).build()

        val call: Call = client.newCall(request)

        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.d(TAG, "onFailure: --------${e.toString()}")
                listener.onError(e)
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d(TAG, "onResponse: --------${response.code}")
                if (!response.isSuccessful) {
                    listener.onError(FileNotFoundException("${response.code}, message = ${response.message}"))
                    return
                }
                val inputStream = response.body!!.byteStream()
                val buffer = ByteArray(1024 * 4)
                var fos: FileOutputStream? = null
                val total = response.body!!.contentLength()
                var sum: Long = 0
                var len = 0
                val off = 0
                try {
                    fos = FileOutputStream(file)
                    while (inputStream.read(buffer).apply { len = this } > 0) {
                        fos.write(buffer, off, len)
                        sum += len.toLong()
                        val progress = (sum * 1.0f / total * 100).toInt()

                        listener.onProgress(progress)

//                        Log.d(TAG, "onResponse: progress = $progress")
                    }
                    fos.flush()
                    fos.close()
                    listener.onSuccess(file.absolutePath)
                } catch (e: Exception) {
                    listener.onError(e)
                    Log.d(TAG, "onResponse: error")
                }
            }

        })

    }
}